<?php
namespace EApiSwoole\Redis;
use Swoole\Database\RedisConfig;
use Swoole\Database\RedisPool;
use EApiSwoole\Foundation\Application;
use RuntimeException;
class Pool{
	protected $app;
	
	protected $config;
	
	protected $pool;
	
	private static $instance;
	protected $redis_config;
	public function __construct(Application $app)
	{
	    $this->app = $app;
	    $this->config = $app->make("config");
	    $this->init();
	}
	
	protected function init()
	{
	    $config = (new RedisConfig)
	              ->withHost($this->config->get("database.redis.host"))
	              ->withPort($this->config->get("database.redis.port"))
	              ->withAuth($this->config->get("database.redis.auth"))
	              ->withDbIndex($this->config->get("database.redis.db_index"))
	              ->withTimeout($this->config->get("database.redis.time_out"));
	    $this->pool = new RedisPool($config,$this->config->get("database.redis.size"));
		$this->redis_config=$config;
		 
	}
	
	
	  public static function getInstance($config = null, $poolName = 'default')
	    {
	        if (empty(self::$instance[$poolName])) {
	            if (empty($config)) {
	                throw new RuntimeException('redis config empty');
	            }
	            if (empty($config['size'])) {
	                throw new RuntimeException('the size of redis connection pools cannot be empty');
	            }
	            self::$instance[$poolName] = new static($config);
	        }
	
	        return self::$instance[$poolName];
	    }
	
	    public function getConnection()
	    {
	        return $this->pool->get();
	    }
	
	    public function close($connection = null)
	    {
	        $this->pool->put($connection);
	    }
	
	    public function getConfig(): array
	    {
	        return $this->redis_config;
	    }
}